using System;
using System.Text.Json;

namespace XSResearch.Configuration
{
    public class AgentSettings
    {
        public double ExplorationRate { get; set; } = 0.3;
        public int MemoryCapacity { get; set; } = 100;
    }

    public class XRSettings
    {
        public int SamplingRate { get; set; } = 60;
        public int ConnectionTimeoutMs { get; set; } = 5000;
    }

    public class AppConfig
    {
        public AgentSettings Agent { get; set; } = new AgentSettings();
        public XRSettings XR { get; set; } = new XRSettings();
        public string LogPath { get; set; } = "app.log";
        public bool EnablePerformanceLogging { get; set; } = true;

        public static AppConfig Load(string path = "config.json")
        {
            try
            {
                if (!File.Exists(path)) return new AppConfig();
                
                var json = File.ReadAllText(path);
                var config = JsonSerializer.Deserialize&lt;AppConfig&gt;(json) ?? new AppConfig();
                
                if (!config.Validate())
                {
                    throw new InvalidOperationException("Invalid configuration values");
                }
                
                return config;
            }
            catch (Exception ex)
            {
                throw new AppConfigException("Failed to load configuration", ex);
            }
        }

        public bool Validate()
        {
            return Agent.ExplorationRate is >= 0 and <= 1 && 
                   Agent.MemoryCapacity > 0 &&
                   XR.SamplingRate > 0 &&
                   XR.ConnectionTimeoutMs > 0;
        }
    }

    public class AppConfigException : Exception
    {
        public AppConfigException(string message, Exception inner) 
            : base(message, inner) { }
    }
}